﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Circle.Domain.Interface.Service;
using Circle.Domain.Entity;
using Circle.Domain.Interface.UnitOfWork;
using Circle.Web.ViewModelsClient;
using Circle.Web.ViewModels;
using System.Web.Mvc;
using Circle.Manager;
using Circle.Domain.Model;
using Circle.Web.Drivers.Contract;

namespace Circle.Web.Drivers
{

    public abstract class OwnerableDriver<VM, CM> :  SavableDriver<VM, CM>
        where VM: OwnerViewModel, new()
        where CM : OwnerClientModel, new()
    {

        public override CM ToClient(VM vModel, CM cModel = null, string[] excludeProperties = null, bool serverStatus = true)
        {
            CM clientModel = base.ToClient(vModel, cModel, excludeProperties, serverStatus);

            clientModel.UserName = vModel.UserName;

            return clientModel;
        }

    }


    public abstract class OwnerableEntityDriver<E, CM> : SavableEntityDriver<E, CM>
        where E : BaseOwnerEntity
        where CM : OwnerClientModel, new()
    {
        public OwnerableEntityDriver(IBaseCrudService<E> service)
            : base(service)
        { }

        public override CM CreateClient(string[] includeProperties = null)
        {
            var clientModel = base.CreateClient(includeProperties);
            if (SecurityManager.CurrentUser != null)
            {
                clientModel.UserName = SecurityManager.CurrentUser.UserName;
            }
            return clientModel;
        }

        public override CM ToClient(E entity, CM cModel = null, string[] excludeProperties = null, bool serverStatus = true)
        {
            if (entity == null) return null;
            CM clientModel = base.ToClient(entity, cModel, excludeProperties, serverStatus);

            if (clientModel.isNew())
            {
                if (SecurityManager.CurrentUser != null)
                {
                    clientModel.UserName = SecurityManager.CurrentUser.UserName;
                }
            }
            else
            {
                clientModel.UserName = entity.User.UserName;
            }
            return clientModel;
        }

        public override E FromClient(E m, CM cModel, string[] includeProperties = null)
        {
            if (m == null || cModel == null) return null;
            return m;
        }
    }
}